package com.ruoyi.bizsys.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.bizsys.domain.AwardGroup;
import com.ruoyi.bizsys.service.IAwardGroupService;
import com.ruoyi.bizsys.vo.AwardGroupVo;
import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.Func;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.bizsys.mapper.UserActivityGroupMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.bizsys.domain.UserActivityGroup;
import com.ruoyi.bizsys.mapper.UserActivityGroupMapper;
import com.ruoyi.bizsys.query.UserActivityGroupQuery;
import com.ruoyi.bizsys.service.IUserActivityGroupService;
import com.ruoyi.bizsys.vo.UserActivityGroupVO;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;


/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author african-loan
 * @date 2022-06-23
 */
@Slf4j
@Service
public class UserActivityGroupServiceImpl extends ServiceImpl<UserActivityGroupMapper, UserActivityGroup> implements IUserActivityGroupService {

    @Autowired
    private IAwardGroupService awardGroupService;

    @Override
    public List<UserActivityGroupVO> selectUserActivityGroupList(UserActivityGroupQuery userActivityGroupQuery) {
        return baseMapper.selectUserActivityGroupList(userActivityGroupQuery);
    }

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】ID
     * @return 【请填写功能名称】
     */
    @Override
    public UserActivityGroup selectUserActivityGroupById(Long id) {
        return this.getById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param userActivityGroup 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<UserActivityGroup> selectUserActivityGroupList(UserActivityGroup userActivityGroup) {
        return this.list(new QueryWrapper<>(userActivityGroup).last("order by id desc"));
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param userActivityGroup 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertUserActivityGroup(UserActivityGroup userActivityGroup) {
        userActivityGroup.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(userActivityGroup);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param userActivityGroup 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateUserActivityGroup(UserActivityGroup userActivityGroup) {
        userActivityGroup.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(userActivityGroup);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteUserActivityGroupByIds(Long[] ids) {
        return baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteUserActivityGroupById(Long id) {
        return baseMapper.deleteById(id);
    }

    @Override
    public int saveAwardGroup(String userId, String awardGroup) {
        return baseMapper.saveAwardGroup(userId, awardGroup);
    }

    @Override
    public UserActivityGroup getByUserId(String userUuid) {
        return getOne(new QueryWrapper<UserActivityGroup>().eq("user_id", userUuid).eq("state", "1"));
    }

    @Override
    @Transactional
    public void updateBatch(List<AwardGroupVo> list) {
        UpdateWrapper<UserActivityGroup> updateWrapper = new UpdateWrapper<>();
        list.forEach(e -> {
            UserActivityGroup userActivityGroup = this.baseMapper.selectOne(new LambdaUpdateWrapper<UserActivityGroup>().eq(UserActivityGroup::getUserId,e.getUserId()));
            if(userActivityGroup==null){
                UserActivityGroup insertEntity = new UserActivityGroup();
                insertEntity.setUserId(e.getUserId());
                insertEntity.setAwardGroupCode(e.getGroupCode());
                this.baseMapper.insert(insertEntity);
            }else{
                UserActivityGroup updateEntity = new UserActivityGroup();
                updateEntity.setAwardGroupCode(e.getGroupCode());
                this.baseMapper.update(updateEntity,new LambdaUpdateWrapper<UserActivityGroup>()
                        .eq(UserActivityGroup::getUserId,e.getUserId()));
            }
        });
    }

    @Override
    @Transactional
    public void saveOrUpdateByUserIds(AwardGroupVo awardGroupVo) {

//        AwardGroup awardGroup = getAwardGroup(awardGroupVo);
        QueryWrapper<UserActivityGroup> queryWrapper = new QueryWrapper<UserActivityGroup>().in("user_id", awardGroupVo.getUserIds()).select("user_id");
        List<String> userIdList = super.list(queryWrapper).stream().map(UserActivityGroup::getUserId).collect(Collectors.toList());

        List<UserActivityGroup> addList = new ArrayList<>();
        List<String> updateList = new ArrayList<>();
        awardGroupVo.getUserIds().forEach(userId -> {
            //userId已存在
            if (userIdList.contains(userId)) {
                updateList.add(userId);
            } else {
                UserActivityGroup userActivityGroup = new UserActivityGroup();
                userActivityGroup.setUserId(userId);
                userActivityGroup.setAwardGroupCode(awardGroupVo.getGroupCode());
                addList.add(userActivityGroup);
            }
        });

        super.saveBatch(addList);
        if (CollectionUtils.isEmpty(updateList)) {
            return;
        }
        super.update(new LambdaUpdateWrapper<UserActivityGroup>()
                .set(UserActivityGroup::getAwardGroupCode, awardGroupVo.getGroupCode())
                .in(UserActivityGroup::getUserId, updateList));
    }

    @Override
    public int insertUserActivityGroup(String userId, String awardQualiFied) {
        log.info("userId:{},awardQualiFied:{}", userId, awardQualiFied);
        assert Func.isNotEmpty(awardQualiFied);
        int userCount = count(new QueryWrapper<UserActivityGroup>().eq("user_id", userId));
        if (userCount == 0) {
            return baseMapper.insertUserActivityGroup(userId, awardQualiFied);
        }
        return userCount;
    }

    private AwardGroup getAwardGroup(AwardGroupVo awardGroupVo) {
        AwardGroup awardGroup = awardGroupService.getById(awardGroupVo.getGroupId());
        if (Func.isEmpty(awardGroup)) {
            log.warn("awardGroup 为空");
            throw new BusinessException(RspEnmu.ILLEGAL_REQ_ERR);
        }
        return awardGroup;
    }

}
